package cn.kgc.service.impl;

import cn.kgc.entity.Industry;
import cn.kgc.mapper.IndustryMapper;
import cn.kgc.service.IndustryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author YC
 */
@Slf4j
@Service("industryService")
public class IndustryServiceImpl extends ServiceImpl<IndustryMapper, Industry> implements IndustryService {

    @Override
    public List<Industry> getTopIndustry() {
        LambdaQueryWrapper<Industry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Industry::getFatherId, 0);
        queryWrapper.orderByAsc(Industry::getSort);
        return list(queryWrapper);
    }

    @Override
    public List<Industry> getThirdIndustry(String topId) {
        // SQL语句：
        // select *
        // from industry
        // where father_id in (select id from industry where father_id = #{topId} )

        // 构建外层查询条件
        LambdaQueryWrapper<Industry> queryWrapper = new LambdaQueryWrapper<>();
        // 构建子查询：查询一级分类下的二级分类ID
        LambdaQueryWrapper<Industry> subQuery = new LambdaQueryWrapper<>();
        subQuery.eq(Industry::getFatherId, topId).select(Industry::getId);
        List<Industry> secondLevelIndustries = baseMapper.selectList(subQuery);

        // 提取二级分类ID列表（过滤空值）
        List<String> secondLevelIds = secondLevelIndustries.stream()
                .filter(industry -> industry.getId() != null && !industry.getId().isEmpty())
                .map(Industry::getId)
                .collect(Collectors.toList());

        // 处理二级分类ID为空的情况（传入的一级分类ID错误或无二级分类）
        if (secondLevelIds.isEmpty()) {
            // 日志记录：方便排查问题
            log.debug("未找到一级分类ID:{}对应的二级分类，返回了空列表", topId);
            return Collections.emptyList();
        }

        // 外层查询：查询二级分类下的三级分类
        queryWrapper.in(Industry::getFatherId, secondLevelIds);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<String> getTopIndustryId() {
        List<Industry> list = list(new LambdaQueryWrapper<Industry>().eq(Industry::getLevel, 1).select(Industry::getId));
        return list.stream().map(Industry::getId).collect(Collectors.toList());
    }
}
